package utils

import (
	"github.com/gdamore/tcell/v2"
	"github.com/mattn/go-runewidth"
	"go-TcellTxt/global"
	"os"
)

// 屏幕内容
var ScreenContent [][]rune

// 判断某一行是否有值
func IsLineContent(y int) bool {
	for _, v := range ScreenContent[y] {
		if v != 0 {
			return true
		}
	}
	return false
}

// 将指定行和他之后的行向下移动一行
func MoveDownLine(y int) {
	for i := global.ScreenHeight - 1; i > y; i-- {
		ScreenContent[i] = ScreenContent[i-1]
	}
	ScreenContent[y] = make([]rune, global.ScreenWidth)
}

// 初始化屏幕当前屏幕大小的ScreenContent
func ScreenContentInit() {
	var newScreenContent = make([][]rune, global.ScreenHeight)
	for i := range newScreenContent {
		newScreenContent[i] = make([]rune, global.ScreenWidth)
	}
	//判断是否有值,如果有值就复制
	if len(ScreenContent) > 0 {
		for i := range ScreenContent {
			for j := range ScreenContent[i] {
				newScreenContent[i][j] = ScreenContent[i][j]
			}
		}
	}
	ScreenContent = newScreenContent
}

// 写入字符串然后移动光标
func InputStrMove(s tcell.Screen, x, y int, style tcell.Style, str string) (int, int) {
	i, i2 := inputStr(s, x, y, style, str)
	MoveCursor(s, i, i2)
	return i, i2
}

func inputStr(s tcell.Screen, x, y int, style tcell.Style, str string) (int, int) {
	for _, c := range str {
		var comb []rune
		w := runewidth.RuneWidth(c)
		if w == 0 {
			comb = []rune{c}
			c = ' '
			w = 1
		}
		ScreenContent[y][x] = c
		s.SetContent(x, y, c, comb, style)
		x += w
	}
	//执行渲染
	global.Screen.Show()
	return x, y
}

// 移动光标
func MoveCursor(s tcell.Screen, x, y int) {
	s.ShowCursor(x, y)
}

// 画一个框
func drawBox(s tcell.Screen, x1, y1, x2, y2 int, style tcell.Style, r rune) {
	if y2 < y1 {
		y1, y2 = y2, y1
	}
	if x2 < x1 {
		x1, x2 = x2, x1
	}

	for col := x1; col <= x2; col++ {
		s.SetContent(col, y1, tcell.RuneHLine, nil, style)
		s.SetContent(col, y2, tcell.RuneHLine, nil, style)
	}
	for row := y1 + 1; row < y2; row++ {
		s.SetContent(x1, row, tcell.RuneVLine, nil, style)
		s.SetContent(x2, row, tcell.RuneVLine, nil, style)
	}
	if y1 != y2 && x1 != x2 {
		// Only add corners if we need to
		s.SetContent(x1, y1, tcell.RuneULCorner, nil, style)
		s.SetContent(x2, y1, tcell.RuneURCorner, nil, style)
		s.SetContent(x1, y2, tcell.RuneLLCorner, nil, style)
		s.SetContent(x2, y2, tcell.RuneLRCorner, nil, style)
	}
	for row := y1 + 1; row < y2; row++ {
		for col := x1 + 1; col < x2; col++ {
			s.SetContent(col, row, r, nil, style)
		}
	}
}

// 选择一块区域
func drawSelect(s tcell.Screen, x1, y1, x2, y2 int, sel bool) {

	if y2 < y1 {
		y1, y2 = y2, y1
	}
	if x2 < x1 {
		x1, x2 = x2, x1
	}
	for row := y1; row <= y2; row++ {
		for col := x1; col <= x2; col++ {
			mainc, combc, style, width := s.GetContent(col, row)
			if style == tcell.StyleDefault {
				style = tcell.StyleDefault.Foreground(tcell.ColorWhite).Background(tcell.ColorBlack)
			}
			style = style.Reverse(sel) //反转
			s.SetContent(col, row, mainc, combc, style)
			col += width - 1
		}
	}
}

// 关闭屏幕
func CloseScreen(s tcell.Screen) {
	s.Fini()
	os.Exit(0)
}
